/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.amqp.rabbitmq.advice;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.tianyun.cloud.context.RequestContext.RequestContextHolder;
import org.tianyun.cloud.context.ServletContext.ServletContextHolder;

import java.util.Map;

/**
 * 消息拦截处理，设置上下文信息
 *
 * @auther ebert_chan
 */
public class ContextAdvice implements MessageAdvice {

    /*
     * @see org.tianyun.cloud.amqp.rabbitmq.advice.ListenerInvokeAdvice#onAfter(java.lang.Object)
     */
    @Override
    public void onAfter(Object value) throws Throwable {
        ServletContextHolder.clear();
    }

    /*
     * @see org.tianyun.cloud.amqp.rabbitmq.advice.MessageAdvice#onBefore(org.springframework.amqp.core.Message)
     */
    @Override
    public void onBefore(Message message) throws Throwable {
        MessageProperties messageProperties = message.getMessageProperties();
        if (messageProperties == null) {
            return;
        }
        Map<String, Object> headers = messageProperties.getHeaders();
        RequestContextHolder.setContextMap(headers);
        ServletContextHolder.setContextMap(headers);
    }

}
